<template>
    <el-card @contextmenu.stop.prevent="context_menu_visible = false" v-loading="tab_list_load">
        <el-scrollbar>
            <el-space wrap :size="62">
                <div class="dir-container _selected" v-for="(item, i) in tab_list" :key="i"
                    @contextmenu.prevent.stop="menu_click($event, item)">
                    <router-link :to="`/detail?id=${item.menu_id}`">
                        <span class="c_date"> {{ item.create_date }} </span>
                        <el-space class="tag-list" wrap :size="4" v-if="item.children && item.children.length > 0">
                            <el-tag disable-transitions="true" effect="dark" v-for="_item in item.children"
                                :key="_item">{{ _item.name }}</el-tag>
                        </el-space>
                        <el-text truncated :title="item.name" class="dir-name" type="primary" size="large">{{ item.name }}</el-text>
                    </router-link>
                </div>
            </el-space>
        </el-scrollbar>
        <ContextMenu @close="context_menu_visible = false" :list="context_menu" :visible="context_menu_visible"
            @command="excuteEvent"></ContextMenu>
    </el-card>
    <el-dialog :destroy-on-close="true" v-model="tab_config.visible" title="创建文件夹" width="480" align-center
        :append-to-body="false">
        <div class="custom-template">
            <el-form ref="formRef" :model="template" label-width="auto" :rules="rules" style="max-width: 600px">
                <el-form-item error="请输入文件夹名字" show-message label="模板名字" prop="name">
                    <el-input maxlength="16" :autofocus="true" v-model="template.name" placeholder="文件夹名字 最多16字" />
                </el-form-item>
                <el-form-item label="文件夹标签" prop="tags">
                    <el-row class="full-content">
                        <el-col>
                            <div class="place-input">
                                <el-space wrap>
                                    <el-tag size="large" v-for="item in template.tags" :key="item.id">{{ item.value
                                        }}</el-tag>
                                </el-space>
                            </div>
                        </el-col>
                    </el-row>
                    <el-divider class="my-divider"></el-divider>
                    <el-row class="full-content">
                        <el-col>
                            <el-space wrap>
                                <el-check-tag closable @close="removeTag(item.id)" v-for="item in template.serverTags"
                                    :key="item.id" :checked="item.checked"
                                    @change="tag_select(item, item.id, $event)">{{ item.value
                                    }}</el-check-tag>
                            </el-space>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="danger" @click="tab_config.visible = false">取消</el-button>
                <el-button type="primary" @click="sumit_template"> 创建 </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="js">
import { ref, reactive, toRaw,h } from "vue";
import { get as http_get,REG_CHAR, post as http_post, URL, str_utils, remove_prop } from '@/tool/common.js';
import { debounce } from "@/tool/screen";
import ContextMenu from "@/components/contextmenu/index.vue";
const formRef = ref();
const tab_config = reactive({
    visible: false
});

const remove_config = reactive({
    value: false,
    id: null,
    name: null,
});
const template = reactive({
    name: "",
    id: "",
    tag: "",
    tag_visible: false,
    tags: [],
    serverTags: [
        {
            id: 0,
            value: "工作",
            checked: false,
            children: [],
        },
        {
            id: 1,
            value: "排期",
            checked: false,
            children: [],
        },
    ],
});
const rules = reactive({
    name: [
        {
            validator: (a, b, c) => {
                return b && b.trim().length > 0;
            },
            trigger: "blur",
        },
    ],
});
const context_menu = ref(null);
const context_menu_visible = ref(false);
const tab_list_load = ref(false);
const tab_list = ref([]);
const de = debounce();
function menu_click(a, b) {
    if (!b || str_utils.is_empty(b.menu_id)) {
        return;
    }
    let pos = {
        x: a.clientX,
        y: a.clientY,
    };
    context_menu_visible.value = true;
    context_menu.value = {
        title: b.name || "暂无",
        list: [
            {
                label: "新建文件夹",
                value: null,
                command: "new_folder",
            },
            {
                label: "刷新",
                value: null,
                command: "refresh"
            },
            {
                label: "删除",
                value: b.menu_id,
                color: "red",
                command: "delete",
            },
            {
                label: "重命名",
                value: b.menu_id,
                command: "rename",
            }
        ],
        position: pos,
    };
}// 拼接数组
function toValue(arr, name, fill = ",") {
    if (!arr) {
        return;
    }
    let str = "";
    arr.forEach((i, b) => {
        str = str + i[name] + `${b === arr.length - 1 ? "" : fill}`;
    });
    return str;
}
function tag_select(a, b, c) {
    a.checked = c;
    if (a.checked) {
        template.tags.push(a);
    } else {
        _.remove(template.tags, function (o) {
            return o.id === b;
        });
    }
    const val = toValue(template.tags, "value");
    template.tag = val;
}
// 重命名文件夹
function rename_template(id, name) {
    ElMessageBox.prompt("请输入新的文件夹名字", "重命名", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        inputValue: name,
        inputValidator: (a) => {
            if (str_utils.not_empty(a)) {
                return !REG_CHAR.test(a) || a === name;
            } else {
                return false;
            }
        },
        inputErrorMessage: "输入无效",
    })
        .then((e) => {
            if (str_utils.is_empty(e.value)) {
                return;
            }
            http_post({
                url: URL.BASE + URL.API_TAB_RENAME,
                data: {
                    id,
                    name: e.value,
                },
            })
                .then((res) => {
                    if (res.code) {
                        ElMessage.success("重命名成功");
                        get_tab_content();
                    } else {
                        throw Exception();
                    }
                })
                .catch(() => {
                    ElMessage.error("重命名失败");
                });
        })
        .catch((err) => void (err));
}
function remove_template(id, name) {
    ElMessageBox({
        title: "确认删除\t" + name + "\t文件夹吗",
        type: "warning",
        showCancelButton: true,
        cancelButtonText: "取消",
        message: () =>
            h(
                "div",
                {
                    class: "box-content",
                },
                [
                    h(ElCheckbox, {
                        modelValue: remove_config.value,
                        label: "彻底删除",
                        size: "large",
                        "onUpdate:modelValue": (val) => {
                            remove_config.value = val;
                        },
                    }),
                ],
                h(
                    ElText,
                    {
                        type: "danger",
                    },
                    "彻底删除之后无法回复，请谨慎操作"
                )
            ),
    })
        .then(() => {
            let config = {
                message: "删除失败！",
                type: "error",
            }; // 消息配置
            http_post({
                url: URL.BASE + URL.API_TAB_DEL,
                data: {
                    id,
                    drop: remove_config.value,
                },
            })
                .then((res) => {
                    if (res && res.code === 200) {
                        config.message = "删除成功！";
                        config.type = "success";
                    }
                })
                .catch((err) => {
                    return err;
                })
                .finally(() => {
                    ElMessage(config);
                    get_tab_content();
                });
        })
        .catch((err) => void(err))
        .finally(() => {
            remove_config.value = false; // 还原
        });
}
// 创建文件夹
// 执行回调
function excuteEvent(ev) {
    let cmd = ev.command;
    let id = ev.value || "#";
    let name = ev.name || "";
    if (str_utils.not_empty(cmd) && str_utils.not_empty(id)) {
        switch (cmd) {
            case "new_folder":
                create_template();
                break;
            case "rename":
                rename_template(id, name);
                break;
            case "delete":
                // 显示删除弹窗
                remove_template(id, name);
                break;
            case "refresh":
                get_tab_content();
                break;
        }
    } else {
        ElMessage.warning("操作失败");
    }
}

function create_template() {
    tab_config.visible = true;
}
function render_to_tab(arr) {
    tab_list.value = arr;
}
function sumit_template() {
    const to_raw = _.clone(toRaw(template));
    const _raw = remove_prop(to_raw, "serverTags", "tag_visible", "tag");
    http_post({
        url: URL.BASE + URL.API_TAB_PUSH,
        data: {
            param: _raw,
        },
    })
        .then((res) => {
            return res.code === 200;
        })
        .catch((err) => {
            console.log("请求错误码", err);
        })
        .finally(() => {
            get_tab_content();
        });
    tab_config.visible = false;
}
function get_tab_content() {
    tab_list_load.value = true;
    de.run(() => {
        http_get({
            url: URL.BASE + URL.API_TAB_LIST,
        })
            .then((res) => {
                if (res && res.length > 0) {
                    tab_list.value = res;
                } else {
                    ElMessage.error("获取文件夹失败");
                }
            })
            .catch((err) => {
                ElMessage.error("获取文件夹失败");
                console.log("log:", err);
            }).finally(() => {
                tab_list_load.value = false;
            });
    }, 380);
}
get_tab_content();
</script>
<style lang="scss" scoped>
.dir-container {
    border:1px dashed transparent;
    background-position: center 10px;
    background-repeat: no-repeat;
    background-size: 80%;
    width: 150px;
    height: 150px;
    overflow: hidden;
    padding-top: 8px;
    position: relative;
    background-image: url('@/assets/image/dir.svg');
    box-sizing: border-box;
    .c_date{
        position: absolute;
        z-index: 2;
        top:-16px;
        display: block;
        height: 16px;
        color: rgb(71, 71, 71);
        font-size: 13.3px;
        background-color: rgb(233, 233, 233);
    }
    &:hover {
        border: 1px dashed rgb(0, 174, 255);
        background-color: rgba(0, 174, 255, 0.5);
    }
    a {
        display: block;
        width: 126px;
        position: relative;
        margin: 12px;
        box-sizing: border-box;
        height: 126px;
        padding: 4px;
        text-decoration: none;

        .dir-name {
            position: absolute;
            bottom: 0px;
            font-weight: bold;
            text-align: center;
            width: 100%;
            left: 0;
        }

        .tag-list {
            margin-top: 40px;
        }
    }
}
</style>